<template>
  <el-dialog :visible.sync="dialogTableVisible" :append-to-body="true" :lock-scroll="false" :title="isEdit?'Edit':'Create'" width="900px" @close="handleCloseDetailDialog">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="100px" style="margin-left:50px;">
      <el-form-item :label="$t('table.area')" required>
        <el-select v-model="postForm.area" clearable placeholder="Please Chose" width="600px">
          <el-option v-for="item in areaOptions" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('table.available')" prop="is_available">
        <el-radio-group v-model="postForm.is_available">
          <el-radio :label="1">{{ $t('table_element.available.on') }}</el-radio>
          <el-radio :label="0">{{ $t('table_element.available.un') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- <el-form-item :label="$t('articlefiles.category_id')">
        <el-select v-model="postForm.category_id" clearable placeholder="Please Chose" width="600px">
          <el-option v-for="item in categoryList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item> -->
      <el-form-item :label="$t('articlefiles.category_id')">
            <el-cascader
              :placeholder="$t('placeholder.select')"
              v-model="postForm.category_id"
              :options="categoryOptions"
              change-on-select
            ></el-cascader>
            <!-- <el-select v-model="temp.category_id" class="filter-item" :placeholder="$t('placeholder.select')">
              <el-option v-for="(item, index) in categoryOptions" :key="index" :label="item.name" :value="item.id" />
            </el-select> -->
          </el-form-item>

      <!-- <el-form-item :label="$t('articlefiles.tag_id')">
        <el-checkbox-group v-model="postForm.tags" :checked="selectTag">
          <el-checkbox v-for="item in tagList" :label="item.id" :key="item.id" :value="item.id">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item> -->

      <el-form-item :label="$t('articlefiles.start_at')" required>
        <el-col :span="20">
          <el-form-item prop="start_at">
            <el-date-picker v-model="postForm.start_at" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('placeholder.date')" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item :label="$t('articlefiles.end_at')" required>
        <el-col :span="20">
          <el-form-item prop="end_at">
            <el-date-picker v-model="postForm.end_at" type="datetime" format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('placeholder.date')" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item :label="$t('table.form')" prop="has_form">
        <el-radio-group v-model="postForm.has_form">
          <el-radio :label="0">{{ $t('table_element.auto_renew.off') }}</el-radio>
          <el-radio :label="1">{{ $t('table_element.auto_renew.on') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('table.attachment')" prop="show_attachment">
        <el-radio-group v-model="postForm.show_attachment">
          <el-radio :label="0">{{ $t('table_element.attachment.hidden') }}</el-radio>
          <el-radio :label="1">{{ $t('table_element.attachment.show') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('table.file')" class="upload-from" >
              <el-upload
                  :headers="header"
                  :on-success="handleFileSuccess"
                  :action="getUploadFileUrl()"
                  class="uploader-demo"
                  name = "file"
                  :file-list="postForm.fileList"
                  style="width: 450px"
                  >
              <el-button size="small" type="primary">{{$t('table.browse')}}</el-button>
            </el-upload>
            <el-input v-model="postForm.file" type="hidden" style="display: none" />
          </el-form-item>

      <el-form-item :label="$t('articlefiles.sort')" prop="sort" >
        <el-col :span="20">
          <el-input v-model="postForm.sort" :label="$t('articlefiles.sort')" type="number" min="1"/>
          <el-input v-model="postForm.type" :label="$t('articlefiles.type')" type="hidden"/>
        </el-col>
      </el-form-item>

      <template>
        <el-tabs v-model="activeName">
          <el-tab-pane label="en" name="first" >

            <el-form-item :label="$t('articlefiles.author')" prop="en_author">
              <el-col :span="20">
                <el-input v-model="postForm.en_author" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.keyword')" prop="en_keyword" >
              <el-col :span="20">
                <el-input v-model="postForm.en_keyword" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.title')" prop="en_title" required>
              <el-col :span="20">
                <el-input v-model="postForm.en_title" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('couponfiles.description')" prop="en_summary" >
              <el-col :span="20">
                <el-input v-model="postForm.en_summary" type="textarea"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.source_path')" prop="en_source_path" >
              <el-col :span="20">
                <el-upload
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  :headers="header"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="en_imageUrl" :src="en_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <el-input v-model="postForm.en_source_path" type="hidden" style="display: none"/>
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('table.content')">
              <el-col :span="20">
                <div class="editor-container">
                  <Tinymce id="fContent" ref="editor1" :height="400" v-model="postForm.en_content" :value="postForm.en_content" />
                </div>
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('articlefiles.link')" prop="en_link" >
              <el-col :span="20">
                <el-input v-model="postForm.en_link" />
              </el-col>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="zh-ch" name="second">
            <el-form-item :label="$t('articlefiles.author')" prop="cn_author">
              <el-col :span="20">
                <el-input v-model="postForm.cn_author" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.keyword')" prop="cn_keyword" >
              <el-col :span="20">
                <el-input v-model="postForm.cn_keyword" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.title')" prop="cn_title">
              <el-col :span="20">
                <el-input v-model="postForm.cn_title" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('couponfiles.description')" prop="cn_summary" >
              <el-col :span="20">
                <el-input v-model="postForm.cn_summary" type="textarea"/>
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('articlefiles.source_path')" prop="cn_source_path" >
              <el-col :span="20">
                <el-upload
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  :headers="header"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="cn_imageUrl" :src="cn_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <el-input v-model="postForm.cn_source_path" type="hidden" style="display: none"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('table.content')">
              <el-col :span="20">
                <div class="editor-container">
                  <Tinymce id="fCNContent" ref="editor2" :height="400" v-model="postForm.cn_content" :value="postForm.cn_content" />
                </div>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.link')" prop="cn_link" >
              <el-col :span="20">
                <el-input v-model="postForm.cn_link" />
              </el-col>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="zh-hk" name="third">
            <el-form-item :label="$t('articlefiles.author')" prop="hk_author">
              <el-col :span="20">
                <el-input v-model="postForm.hk_author" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.keyword')" prop="hk_keyword" >
              <el-col :span="20">
                <el-input v-model="postForm.hk_keyword" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.title')" prop="hk_title">
              <el-col :span="20">
                <el-input v-model="postForm.hk_title" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('couponfiles.description')" prop="hk_summary" >
              <el-col :span="20">
                <el-input v-model="postForm.hk_summary" type="textarea"/>
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('articlefiles.source_path')" prop="hk_source_path" >
              <el-col :span="20">
                <el-upload
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  :headers="header"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="hk_imageUrl" :src="hk_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <el-input v-model="postForm.hk_source_path" type="hidden" style="display: none"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('table.content')">
              <el-col :span="20">
                <div class="editor-container">
                  <Tinymce id="fHKContent" ref="editor3" :height="400" v-model="postForm.hk_content" :value="postForm.hk_content" />
                </div>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.link')" prop="hk_link" >
              <el-col :span="20">
                <el-input v-model="postForm.hk_link" />
              </el-col>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="zh-tw" name="fourth">
            <el-form-item :label="$t('articlefiles.author')" prop="tw_author">
              <el-col :span="20">
                <el-input v-model="postForm.tw_author" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.keyword')" prop="tw_keyword" >
              <el-col :span="20">
                <el-input v-model="postForm.tw_keyword" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.title')" prop="tw_title">
              <el-col :span="20">
                <el-input v-model="postForm.tw_title" />
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('couponfiles.description')" prop="tw_summary" >
              <el-col :span="20">
                <el-input v-model="postForm.tw_summary" type="textarea"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.source_path')" prop="tw_source_path" >
              <el-col :span="20">
                <el-upload
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  :headers="header"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="tw_imageUrl" :src="tw_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <el-input v-model="postForm.tw_source_path" type="hidden" style="display: none"/>
              </el-col>
            </el-form-item>
            <el-form-item :label="$t('table.content')">
              <el-col :span="20">
                <div class="editor-container">
                  <Tinymce id="fTWContent" ref="editor4" :height="400" v-model="postForm.tw_content" :value="postForm.tw_content" />
                </div>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('articlefiles.link')" prop="tw_link" >
              <el-col :span="20">
                <el-input v-model="postForm.tw_link" />
              </el-col>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </template>
    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDetailDialog">{{ $t('table.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm('postForm')">{{ $t('table.submit') }}</el-button>
    </div>
  </el-dialog>

</template>
<script>

import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload/singleImage3'
import articleApi from '@/api/article/article'
import articleCategoryApi from '@/api/article/articlecategory'
import { fetchFile } from '@/api/upload'
import { getUploadImageUrl, getUploadFileUrl } from '@/utils'
import i18n from '@/lang/index'
import { getToken } from '@/utils/auth'

const defaultForm = {
  is_available: 1,
  area: '',
  category_id: [],
  tags: [],
  fileList: [],
  type: '',
  status: 0,
  start_at: '',
  end_at: '',
  sort: 999999999,
  show_attachment: 0,
  has_form: 0,
  file_url: '',
  file: '',

  en_keyword: '',
  en_title: '',
  en_author: '',
  en_summary: '',
  en_source_path: '',
  en_link: '',
  en_content: '',
  en_imgpath: '',

  cn_keyword: '',
  cn_title: '',
  cn_author: '',
  cn_summary: '',
  cn_type: '',
  cn_source_path: '',
  cn_link: '',
  cn_start_at: '',
  cn_end_at: '',
  cn_content: '',
  cn_imgpath: '',

  hk_keyword: '',
  hk_title: '',
  hk_author: '',
  hk_summary: '',
  hk_source_path: '',
  hk_link: '',
  hk_content: '',
  hk_imgpath: '',

  tw_keyword: '',
  tw_title: '',
  tw_author: '',
  tw_summary: '',
  tw_source_path: '',
  tw_link: '',
  tw_content: '',
  tw_imgpath: ''
}

export default {
  name: 'Detail',
  components: { Tinymce, Upload },
   props: {
    categoryOptions: {
      type: Array,
      default: []
    }
  },
  data() {
    return {
      activeName: 'first',
      postForm: Object.assign({}, defaultForm),
      rules: {
      },
      header:{
        'X-Token': getToken()
      },
      en_imageUrl: '',
      cn_imageUrl: '',
      hk_imageUrl: '',
      tw_imageUrl: '',
      isEdit: false,
      recordid: 0,
      imageAction: '',
      dialogTableVisible: false,
      areaOptions: [],
      // categoryList: [],
      // categoryOptions: [],
      tagList: [],
      selectTag: [],
        tinyMceInit: false,
      fileList: []

    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    
    // this.getCategoryList()
  },

  mounted() {
    if (this.isEdit) {
      const id = this.editId || (this.$route.params && this.$route.params.id)
      this.showRecord(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
  },

  methods: {
    showRecord(id) { //edit

      let _this = this
      articleApi.showRecord(id).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.postForm = Object.assign({}, this.postForm, serviceResponse.data.record)
          this.en_imageUrl = this.postForm.en_source_path.indexOf('http')==0 ? this.postForm.en_source_path : this.postForm.en_source_path ? (this.postForm.imageDomain + this.postForm.en_source_path) : ''
          this.cn_imageUrl = this.postForm.cn_source_path.indexOf('http')==0 ? this.postForm.cn_source_path : this.postForm.cn_source_path ? (this.postForm.imageDomain + this.postForm.cn_source_path) : ''
          this.hk_imageUrl = this.postForm.hk_source_path.indexOf('http')==0 ? this.postForm.hk_source_path : this.postForm.hk_source_path ? (this.postForm.imageDomain + this.postForm.hk_source_path) : ''
          this.tw_imageUrl = this.postForm.tw_source_path.indexOf('http')==0 ? this.postForm.tw_source_path : this.postForm.tw_source_path ? (this.postForm.imageDomain + this.postForm.tw_source_path) : ''
          // this.categoryList = serviceResponse.data.categoryList
          // this.tagList = serviceResponse.data.tagList
          // this.selectTag = serviceResponse.data.selectTag
          this.postForm.category_id = serviceResponse.data.selectCategory

          this.$nextTick(() => {
            this.$refs.editor1.destroyTinymce()
            this.$refs.editor1.initTinymce()
            this.$refs.editor2.destroyTinymce()
            this.$refs.editor2.initTinymce()
            this.$refs.editor3.destroyTinymce()
            this.$refs.editor3.initTinymce()
            this.$refs.editor4.destroyTinymce()
            this.$refs.editor4.initTinymce()
            if (_this.activeName === 'first') {
              _this.$refs.editor1.setContent(_this.postForm.en_content)
            }
            if (_this.activeName === 'second') {
              _this.$refs.editor2.setContent(_this.postForm.cn_content)
            }
            if (_this.activeName === 'third') {
              _this.$refs.editor3.setContent(_this.postForm.hk_content)
            }
            if (_this.activeName === 'fourth') {
              _this.$refs.editor4.setContent(_this.postForm.tw_content)
            }
          });
          this.tinyMceInit = true;
        }

      }).catch(err => {
        console.log(err)
      })
    },

    handleCreateRecord() {
      // this.$nextTick(() => {
      //   this.$refs.editor1.destroyTinymce()
      //   this.$refs.editor1.initTinymce()
      //   this.$refs.editor2.destroyTinymce()
      //   this.$refs.editor2.initTinymce()
      //   this.$refs.editor3.destroyTinymce()
      //   this.$refs.editor3.initTinymce()
      //   this.$refs.editor4.destroyTinymce()
      //   this.$refs.editor4.initTinymce()
      //   this.$refs.editor1.setContent('')
      //   this.$refs.editor2.setContent('')
      //   this.$refs.editor3.setContent('')
      //   this.$refs.editor4.setContent('')
      // })

      const params = {
        lang: i18n.locale
      }

      /* articleApi.createRecord(params).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.categoryList = serviceResponse.data.categoryList
          // this.tagList = serviceResponse.data.tagList
        }
      }).catch(err => {
        console.log(err)
      }) */
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.postForm.lang = i18n.locale
          if (this.editId > 0) {
            articleApi.updateRecord(this.editId, this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  message: 'success',
                  type: 'success'
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  message: 'error',
                  type: 'error'
                })
              }
            })
          } else {
            articleApi.storeRecord(this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  message: 'success',
                  type: 'success'
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  message: 'error',
                  type: 'error'
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    getUploadImageUrl() {
      return getUploadImageUrl()
    },
    getUploadFileUrl() {
      return getUploadFileUrl()
    },

    handleImagesSuccess(res, file) {
      if (res.code === 0) {
        if (this.activeName === 'first') {
          this.postForm.en_source_path = res.data.paths[0].path
          this.en_imageUrl = (res.data.paths[0].path.indexOf('http')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.data.paths[0].path
        }
        if (this.activeName === 'second') {
          this.postForm.cn_source_path = res.data.paths[0].path
          this.cn_imageUrl = (res.data.paths[0].path.indexOf('http')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.data.paths[0].path
        }
        if (this.activeName === 'third') {
          this.postForm.hk_source_path = res.data.paths[0].path
          this.hk_imageUrl = (res.data.paths[0].path.indexOf('http')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.paths[0].path
        }
        if (this.activeName === 'fourth') {
          this.postForm.tw_source_path = res.data.paths[0].path
          this.tw_imageUrl = (res.data.paths[0].path.indexOf('http')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.data.paths[0].path
        }
      } else {
        alert(res.data.msg)
      }
    },
    handShowDetailDialog(id) {
      // this.categoryList = []
      defaultForm.category_id = []
      this.tagList = []
      this.selectTag = []
      this.imageUrl = ''

      if (id > 0) {
        this.isEdit = true
        this.editId = id
        this.showRecord(id)
      } else {
        this.isEdit = false
        this.editId = 0
        this.handleCreateRecord()
        this.postForm = Object.assign({}, defaultForm)
      }
      this.getAreaOptions()
      this.reseteditor()
      this.dialogTableVisible = true
    },
    handleCloseDetailDialog() {
      this.resetForm('postForm')
      this.editId = 0
      this.$emit('indexRecord')
      this.en_imageUrl = ''
      this.cn_imageUrl = ''
      this.hk_imageUrl = ''
      this.tw_imageUrl = ''
      this.activeName = 'first'
      this.dialogTableVisible = false
        Tinymce.editors = [];
    },
    getAreaOptions() {
      this.areaOptions = this.$store.state.locale.areas
    },
    reseteditor() {
      this.$nextTick(() => {
        this.$refs.editor1.destroyTinymce()
        this.$refs.editor1.initTinymce()
        this.$refs.editor2.destroyTinymce()
        this.$refs.editor2.initTinymce()
        this.$refs.editor3.destroyTinymce()
        this.$refs.editor3.initTinymce()
        this.$refs.editor4.destroyTinymce()
        this.$refs.editor4.initTinymce()
        this.$refs.editor1.setContent('')
        this.$refs.editor2.setContent('')
        this.$refs.editor3.setContent('')
        this.$refs.editor4.setContent('')
      })
    },
    // getCategoryList() {
    //   articleCategoryApi.fetchCategoryTree().then(response => {
    //     var data = response.data
    //     this.categoryOptions = data.data
    //   });
    // },
    handleFileSuccess(res, file) {
      this.postForm.file = '';
      this.postForm.fileList = [];
      if (res.flag == 1) {
        var filepath = res.data[0].path;
        var filename = filepath.substring(filepath.lastIndexOf("/") + 1);
        this.postForm.file = filepath;
        this.postForm.fileList = [{ name: filename, url: filepath }]
      }
    },
    handleClick(tab, event) {
      console.log(tab, event)
    }
  }

}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    max-width: 178px;
    display: block;
  }
</style>
